package com.friends.common.web.interceptor;

import com.friends.common.web.annotation.RoleAuth;
import com.friends.common.web.baseentity.BaseActorEntity;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 角色验权
 * Created by xiajiangge on 2017/2/22.
 */
public class RoleauthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            Method method = handlerMethod.getMethod();
            RoleAuth annotation = method.getAnnotation(RoleAuth.class);
            if (annotation == null) return true;
            String[] roles = annotation.roles();
            if(roles.length < 1 ) return true;

            Object rolesO = request.getSession().getAttribute("userRoles");
            if(rolesO==null) {
                request.getRequestDispatcher("/home/login.html").forward(request, response);
                return false;
            }

            List<BaseActorEntity> userRoles = (List<BaseActorEntity>)request.getSession().getAttribute("userRoles");
            //有该注解需要验权
            boolean hasRole = false;
            for(int i = 0 ;i<userRoles.size();i++) {
                if (ArrayUtils.contains(roles, userRoles.get(i).getActorid())) {
                    return true;
                }
            }
//            System.out.println("角色："+roles[0]);
            //获取登录用户角色信息,没有则跳转至登录页，有则继续验证
            //校验用户角色是否存在注解角色中
            //如果存在则返回true，否则跳转至无权限提示页
            request.getRequestDispatcher("/home/login.html").forward(request, response);
            return false;
        } else {
            return super.preHandle(request,response,handler);
        }
    }

}
